package handlers

import (
	"context"
	"ourplansystem/server/database"
	"ourplansystem/server/ent"
	"ourplansystem/server/models"
	"time"

	"github.com/gofiber/fiber/v2"
	"github.com/golang-jwt/jwt/v5"
)

// JWT 密钥（生产环境应从环境变量读取）
var jwtSecret = []byte("ourplansystem_secret_key_2025")

// AuthHandler 认证处理器
type AuthHandler struct {
	client *ent.Client
}

// NewAuthHandler 创建认证处理器
func NewAuthHandler(client *ent.Client) *AuthHandler {
	return &AuthHandler{client: client}
}

// JWTClaims JWT 声明
type JWTClaims struct {
	UserID      int64  `json:"user_id"`
	Username    string `json:"username"`
	DisplayName string `json:"display_name"`
	jwt.RegisteredClaims
}

// GenerateToken 生成 JWT Token
func GenerateToken(userID int64, username, displayName string) (string, error) {
	claims := JWTClaims{
		UserID:      userID,
		Username:    username,
		DisplayName: displayName,
		RegisteredClaims: jwt.RegisteredClaims{
			ExpiresAt: jwt.NewNumericDate(time.Now().Add(9999 * 24 * time.Hour)), // 9999天过期
			IssuedAt:  jwt.NewNumericDate(time.Now()),
			NotBefore: jwt.NewNumericDate(time.Now()),
		},
	}

	token := jwt.NewWithClaims(jwt.SigningMethodHS256, claims)
	return token.SignedString(jwtSecret)
}

// LoginRequest 登录请求
type LoginRequest struct {
	Username string `json:"username"`
	Password string `json:"password"`
}

// LoginResponse 登录响应
type LoginResponse struct {
	Token string       `json:"token"`
	User  UserResponse `json:"user"`
}

// Login 用户登录
func (h *AuthHandler) Login(c *fiber.Ctx) error {
	ctx := context.Background()
	var req LoginRequest
	if err := c.BodyParser(&req); err != nil {
		return models.BadRequest(c, "请求参数错误")
	}

	if req.Username == "" {
		return models.BadRequest(c, "用户名不能为空")
	}

	if req.Password == "" {
		return models.BadRequest(c, "密码不能为空")
	}

	// 查询用户
	user, err := database.GetUserByUsername(ctx, h.client, req.Username)
	if err != nil {
		return models.BadRequest(c, "用户名或密码错误")
	}

	// 验证密码
	if err := database.VerifyPassword(user.Password, req.Password); err != nil {
		return models.BadRequest(c, "用户名或密码错误")
	}

	// 生成 JWT Token
	token, err := GenerateToken(user.ID, user.Username, user.DisplayName)
	if err != nil {
		return models.InternalServerError(c, "生成Token失败")
	}

	// 返回用户信息（不包含密码）和 Token
	response := LoginResponse{
		Token: token,
		User: UserResponse{
			ID:          user.ID,
			Username:    user.Username,
			DisplayName: user.DisplayName,
			Avatar:      user.Avatar,
			CreatedAt:   user.CreatedAt.Format("2006-01-02 15:04:05"),
			UpdatedAt:   user.UpdatedAt.Format("2006-01-02 15:04:05"),
		},
	}

	return models.SuccessWithMessage(c, "登录成功", response)
}
